// Ionic Starter App

// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.services' is found in services.js
// 'starter.controllers' is found in controllers.js
angular.module('starter',
  ['ionic-native-transitions','ngIOS9UIWebViewPatch','rt.resize','ionic','ngCordova','ngStorage','lokijs', 'starter.controllers', 'starter.services', 'starter.router', 'starter.config', 'ionic-cache-src', 'starter.directive','ionic.ui.modalService','starter.spmsCacheService'])

  .run(function ($cordovaNetwork,$ionicPlatform,$cordovaSplashscreen,$cordovaToast,$dfCache,$state,$timeout,$dfDB,$ionicHistory,$dfUtil,$location,$rootScope,$cordovaKeyboard,$region,
                 $design,$lookup,$ionicLoading,$interval,$task,$ionicNativeTransitions,$log) {
    $ionicPlatform.ready(function () {
      // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
      // for form inputs)
      if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
        cordova.plugins.Keyboard.hideKeyboardAccessoryBar(false);
        cordova.plugins.Keyboard.disableScroll(false);

        //$ionicNativeTransitions.enable(true);

        if (typeof(cordova.file) == 'undefined')
          console.log("FILE IS UNDEFINED");
        else
          console.log("IT WORKS! YEAH");

        if (window.StatusBar) {
          // org.apache.cordova.statusbar required
          StatusBar.styleDefault();
        }

          $dfDB.initDB();

      }
      if($dfUtil.isEmptyObject(ionic.Platform.device())){
        $dfDB.initDB();

        // $timeout(function(){
        //
        // },1000);
      }

      var isOnline = $cordovaNetwork.isOnline()
      var isOffline = $cordovaNetwork.isOffline()

      $rootScope.networkState =  $cordovaNetwork.getNetwork() ;
      // listen for Online event
      $rootScope.$on('$cordovaNetwork:online', function(event, networkState){
        var type = $cordovaNetwork.getNetwork()
        var onlineState = networkState;
        if (type == Connection.WIFI) {
          $rootScope.networkState = type ;
        }else if (type == Connection.CELL_4G || type == Connection.CELL_3G){
          //TODO something
          $rootScope.networkState = type ;
        }
      })

      // listen for Offline event
      $rootScope.$on('$cordovaNetwork:offline', function(event, networkState){
        var offlineState = networkState;
        //$ionicLoading.show({
        //  template: '网络异常，不能连接到服务器！'
        //});
        $rootScope.networkState = Connection.NONE ;
      });

      $timeout(function(){
        $task.startToUploadAll();
      },2000);

      window.plugins.jPushPlugin.init();
      window.plugins.jPushPlugin.setAlias("");

      window.plugins.jPushPlugin.setBadge(0);
      window.plugins.jPushPlugin.setApplicationIconBadgeNumber(0);

      function onReceiveNotification(){
        var alertContent
        if(device.platform == "Android") {
          alertContent = event.alert;
        } else {
          alertContent = event.aps.alert;
        }
        $log.log(JSON.stringify(event));
        //$rootScope.listStatus = event.extras.status ;
        //alert("recive Notificaiton:" + alertContent);
        if(event.extras && event.extras.status) {
          $rootScope.listStatus = event.extras.status ;
        }else {
          $rootScope.listStatus = event.status ;
        }
      }

      function onFontReceiveNotification(){
        var alertContent
        if(device.platform == "Android") {
          alertContent = event.alert;
        } else {
          alertContent = event.aps.alert;
        }

        //window.plugins.jPushPlugin.setBadge(0);
        //window.plugins.jPushPlugin.setApplicationIconBadgeNumber(0);

        $log.log(JSON.stringify(event));
        //$rootScope.listStatus = event.extras.status ;
        //alert("recive Notificaiton:" + alertContent);
        if(event.extras && event.extras.status) {
          $rootScope.listStatus = event.extras.status ;
        }else {
          $rootScope.listStatus = event.status ;
        }
      }

      document.addEventListener("jpush.receiveNotification", onFontReceiveNotification, false);
      document.addEventListener("jpush.backgroundNotification", onReceiveNotification, false);


      function onOpenNotification(){
        var alertContent;
        if(device.platform == "Android") {
          alertContent = event.alert;
        } else {
          alertContent = event.aps.alert;
          try{
            window.plugins.jPushPlugin.setBadge(0);
            window.plugins.jPushPlugin.setApplicationIconBadgeNumber(0);
          }catch (e){
            $log.log(JSON.stringify(e));
            $log.log(e);
          }
        }
        $log.log(JSON.stringify(event));
        //alert("open Notificaiton:" + alertContent);
        if(event.extras && event.extras.status) {
          $rootScope.listStatus = event.extras.status ;
        }else {
          $rootScope.listStatus = event.status ;
        }
      }
      document.addEventListener("jpush.openNotification", onOpenNotification, false);

    });

    //物理返回按钮控制&双击退出应用
    $ionicPlatform.registerBackButtonAction(function (e) {
      if(cordova.plugins.Keyboard.isVisible){
        cordova.plugins.Keyboard.closeKeyboard();
        return;
      }

      if (window.hammerBgShow) {
        window.hideHammer(e);
        return;
      }

      if ($location.path() == "/tab/project-track/project-log"){
        $rootScope.$broadcast("backToLast");
      }

      if ($location.path() == "/tab/tasks/delivery"
        || $location.path() == "/tab/tasks/delivery/scan"){
        if ($rootScope.scanIn){
          $rootScope.scanIn = false;
          return false;
        } else{
          $ionicHistory.goBack();
        }
      } else{
        //判断处于哪个页面时双击退出
        if ($location.path() == "/guideTemp"
          || $location.path() == "/login"
          || $location.path() == "/tab/tasks"
          || $location.path() == "/tab/chats"
          || $location.path() == "/tab/my"
          || $location.path() == "/tab/htjd"
          || $location.path() == "/tab/projectFollow"
          || $location.path() == "/tab/project-track"){

          // 判断是否为项目跟踪的内容页面
          if ($rootScope.isProjectTrackContent){
            $rootScope.$broadcast("hideContent");
          } else{
            if ($rootScope.backButtonPressedOnceToExit){
              ionic.Platform.exitApp();
            } else{
              $rootScope.backButtonPressedOnceToExit = true;
              $cordovaToast.showShortBottom("再按一次退出系统");
              $timeout(function () {
                $rootScope.backButtonPressedOnceToExit = false;
              },2000);
            }
          }
        } else if ($ionicHistory.backView()){
          if ($cordovaKeyboard.isVisible()){
            $cordovaKeyboard.close();
          } else {
            $ionicHistory.goBack();
          }
        }else{
          $rootScope.backButtonPressedOnceToExit = true;
          $timeout(function () {
            $rootScope.backButtonPressedOnceToExit = false;
          },2000);
        }

        // else{
        //   $rootScope.backButtonPressedOnceToExit = true;
        //   $cordovaToast.showShortBottom("再按一次退出系统");
        //   $timeout(function () {
        //     $rootScope.backButtonPressedOnceToExit = false;
        //   },2000);
        // }

        e.preventDefault();
        return false;
      }
    },101);
  })

  .factory('modalsService', ['appModalService', function (appModalService) {
    // all app modals here
    var service = {
      //datePicker: datePicker
      choiceCity: choiceCity
    };

    return service;

    function choiceCity(parameters) {
      return appModalService.show('templates/city-choice.html', 'ModalDialogCtrl as vm', parameters);
    }

  }])

  //.controller('AppCtrl', ['vm', 'modalsService', function (vm, modalsService) {
  //
  //  var vm = this;
  //
  //  vm.openDateDialog = function () {
  //    modalsService.datePicker({
  //      events: {
  //        ok: 'date-modal:ok',
  //        cancel: 'date-modal:cancel'
  //      }
  //    });
  //  };
  //
  //  vm.$on("date-modal:ok", function (event, data) {
  //    console.log("ok", event, data)
  //    vm.selectedDate = data.selectedDate;
  //  });
  //
  //  vm.$on("date-modal:cancel", function (event, data) {
  //    console.log("cancel", event, data)
  //  });
  //
  //}])

  .controller('ModalDialogCtrl', function ($scope,$rootScope, parameters,$log,$timeout,$ionicScrollDelegate,$region) {

    var vm = $scope;

    vm.okButton = function (data) {
      data = {
        'pro': vm.pros[vm.scrollProperty.scrollOneIndex],
        'city': vm.pros[vm.scrollProperty.scrollOneIndex].cityList[vm.scrollProperty.scrollTwoIndex],
        'town': vm.pros[vm.scrollProperty.scrollOneIndex].cityList[vm.scrollProperty.scrollTwoIndex].regionList[vm.scrollProperty.scrollThreeIndex]
      };

      if (parameters.events.ok)
        $rootScope.$broadcast(parameters.events.ok, data);
      vm.closeModal();
    }

    vm.cancelButton = function (data) {
      if (parameters.events.cancel)
        $rootScope.$broadcast(parameters.events.cancel, data);
      vm.closeModal();
    }

    vm.executeScroll = function() {
      //$log.log($ionicScrollDelegate.$getByHandle('scrollOne').getScrollPosition());
    }

    vm.scrollProperty = {};

    vm.scroll = {
      'scrollPro':[],
      'scrollCity':[],
      'scrollTow':[]
    };

    vm.releaseFromScrollOne = function() {
      $timeout(function(){
        var oneHandle ;
        var twoHandle ;
        var threeHandle ;
        angular.forEach($ionicScrollDelegate._instances, function (s) {
          console.log(s.$$delegateHandle);
          if (s.$$delegateHandle === "scrollOne") {
            oneHandle = s ;
          }else if(s.$$delegateHandle === "scrollTwo") {
            twoHandle = s ;
          }else if(s.$$delegateHandle === "scrollThree") {
            threeHandle = s ;
          }
        });
        var scrollOneY = oneHandle.getScrollPosition().top ;

        var leftIndex = vm.scrollProperty.scrollOneIndex ;
        if(scrollOneY % 53 > 27) {
          oneHandle.scrollTo(0,scrollOneY + (53 - (scrollOneY % 53)),true);
          vm.scrollProperty.scrollOneIndex = (scrollOneY + (53 - (scrollOneY % 53))) / 53 ;
        }else {
          oneHandle.scrollTo(0,scrollOneY - (scrollOneY % 53),true);
          vm.scrollProperty.scrollOneIndex = (scrollOneY - (scrollOneY % 53)) / 53 ;
        }

        if(leftIndex == vm.scrollProperty.scrollOneIndex) {
          return ;
        }

        vm.scrollProperty.scrollTwoIndex = 0 ;
        vm.scrollProperty.scrollThreeIndex = 0 ;

        vm.scrollProperty.scrollTowArray = vm.pros[vm.scrollProperty.scrollOneIndex].cityList ;
        vm.scrollProperty.scrollThreeArray = vm.pros[vm.scrollProperty.scrollOneIndex].cityList[0].regionList ;

        twoHandle.scrollTop();
        threeHandle.scrollTop();
      },1);

      //$log.log(scrollOneY);
    }

    vm.releaseFromScrollTwo = function() {
      $timeout(function(){
        var oneHandle ;
        var twoHandle ;
        var threeHandle ;
        angular.forEach($ionicScrollDelegate._instances, function (s) {
          console.log(s.$$delegateHandle);
          if (s.$$delegateHandle === "scrollOne") {
            oneHandle = s ;
          }else if(s.$$delegateHandle === "scrollTwo") {
            twoHandle = s ;
          }else if(s.$$delegateHandle === "scrollThree") {
            threeHandle = s ;
          }
        });
        var scrollOneY = twoHandle.getScrollPosition().top ;

        var leftIndex = vm.scrollProperty.scrollTwoIndex ;

        if(scrollOneY % 53 > 27) {
          twoHandle.scrollTo(0,scrollOneY + (53 - (scrollOneY % 53)),true);
          vm.scrollProperty.scrollTwoIndex = (scrollOneY + (53 - (scrollOneY % 53))) / 53 ;
        }else {
          twoHandle.scrollTo(0,scrollOneY - (scrollOneY % 53),true);
          vm.scrollProperty.scrollTwoIndex = (scrollOneY - (scrollOneY % 53)) / 53 ;
        }

        if(leftIndex == vm.scrollProperty.scrollTwoIndex) {
          return ;
        }

        vm.scrollProperty.scrollThreeArray = vm.pros[vm.scrollProperty.scrollOneIndex].cityList[vm.scrollProperty.scrollTwoIndex].regionList;
        //twoHandle.scrollTop();
        threeHandle.scrollTop();
      },1);
    }

    vm.releaseFromScrollThree = function() {
      $timeout(function(){
        var oneHandle ;
        var twoHandle ;
        var threeHandle ;
        angular.forEach($ionicScrollDelegate._instances, function (s) {
          console.log(s.$$delegateHandle);
          if (s.$$delegateHandle === "scrollOne") {
            oneHandle = s ;
          }else if(s.$$delegateHandle === "scrollTwo") {
            twoHandle = s ;
          }else if(s.$$delegateHandle === "scrollThree") {
            threeHandle = s ;
          }
        });
        var scrollOneY = threeHandle.getScrollPosition().top ;
        console.log(scrollOneY);

        if(scrollOneY % 53 > 27) {
          threeHandle.scrollTo(0,scrollOneY + (53 - (scrollOneY % 53)),true);
          vm.scrollProperty.scrollThreeIndex = (scrollOneY + (53 - (scrollOneY % 53))) / 53 ;
        }else {
          threeHandle.scrollTo(0,scrollOneY - (scrollOneY % 53),true);
          vm.scrollProperty.scrollThreeIndex = (scrollOneY - (scrollOneY % 53)) / 53 ;
        }


        //vm.scrollProperty.scrollTowArray = vm.pros[vm.scrollProperty.scrollOneIndex].next ;
        //vm.scrollProperty.scrollThreeArray = vm.pros[vm.scrollProperty.scrollOneIndex].next[vm.scrollProperty.scrollTwoIndex].next ;

        //twoHandle.scrollTop();
      },1);
      //$log.log(scrollOneY);
    }

    var isFirst = true;

    $timeout(function(){
      var obj = angular.copy($region.get());

      if(parameters.haveAll && isFirst) {
        isFirst = false;
        for(var i = 0; i < obj.data.length; i++) {
          var newCityList = [{cityCode:'0',cityName:'全部',regionList:[]}];
          obj.data[i].cityList = newCityList.concat(obj.data[i].cityList);

          for(var j = 0; j < obj.data[i].cityList.length; j++) {
            var newRegionList = [{regionCode:'0',regionName:'全部'}];
            obj.data[i].cityList[j].regionList = newRegionList.concat(obj.data[i].cityList[j].regionList);
          }

        }

      }
      vm.pros = obj.data ;
    },20);

    $timeout(function(){
      vm.releaseFromScrollOne();
      var oneHandle ;
      var twoHandle ;
      var threeHandle ;
      angular.forEach($ionicScrollDelegate._instances, function (s) {
        console.log(s.$$delegateHandle);
        if (s.$$delegateHandle === "scrollOne") {
          oneHandle = s ;
        }else if(s.$$delegateHandle === "scrollTwo") {
          twoHandle = s ;
        }else if(s.$$delegateHandle === "scrollThree") {
          threeHandle = s ;
        }
      });

      //for(var i = 0 ; i < pros ; i ++){
        //if(pros[i].provinceCode == )
      //}
    },500);
  });
